<template>
  <el-dialog
    v-model="dialogVisible"
    title="发表评价"
    width="500px"
    @close="handleClose"
  >
    <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
      <el-form-item label="评分" prop="rating">
        <el-rate
          v-model="form.rating"
          :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
          show-text
          :texts="['极差', '失望', '一般', '满意', '惊喜']"
        />
      </el-form-item>
      
      <el-form-item label="评价内容" prop="content">
        <el-input
          v-model="form.content"
          type="textarea"
          :rows="5"
          placeholder="请分享你的体验，帮助其他用户更好地了解..."
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">
        提交评价
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { createReview } from '@/api/review'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  appointmentId: {
    type: Number,
    required: true
  },
  revieweeId: {
    type: Number,
    required: true
  }
})

const emit = defineEmits(['update:visible', 'success'])

const dialogVisible = ref(false)
const formRef = ref(null)
const submitting = ref(false)

const form = ref({
  appointmentId: null,
  revieweeId: null,
  rating: 5,
  content: ''
})

const rules = {
  rating: [
    { required: true, message: '请选择评分', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入评价内容', trigger: 'blur' },
    { min: 10, message: '评价内容至少10个字', trigger: 'blur' }
  ]
}

watch(() => props.visible, (val) => {
  dialogVisible.value = val
  if (val) {
    form.value.appointmentId = props.appointmentId
    form.value.revieweeId = props.revieweeId
  }
})

watch(dialogVisible, (val) => {
  emit('update:visible', val)
})

const handleClose = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    submitting.value = true
    await createReview(form.value)
    
    ElMessage.success('评价成功')
    emit('success')
    handleClose()
  } catch (error) {
    if (error !== false) {
      console.error('评价失败：', error)
    }
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.el-rate {
  height: 40px;
  display: flex;
  align-items: center;
}
</style>

